package com.yb.xczx.cloud.passport.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.model.XczxResult;
import com.yb.xczx.cloud.oauth2.client.bean.XczxOauth2ClientProperties;
import com.yb.xczx.cloud.passport.bean.LoginKeyResult;
import com.yb.xczx.cloud.passport.bean.Oauth2TokenResult;
import com.yb.xczx.cloud.passport.feign.client.AuthBasicClient;
import com.yb.xczx.cloud.passport.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriBuilder;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/24 18:03
 * FileName: Oauth2LoginController
 * Description:
 */

@Controller
@Slf4j
public class Oauth2AuthLoginController implements EnvironmentAware, InitializingBean {
    @Autowired
    private AuthBasicClient authClient;

    @Autowired
    XczxOauth2ClientProperties xczxOauth2ClientProperties;

    public Oauth2AuthLoginController(){
        CacheUtil.resultMap.put("xyz",null);
    }
    public int port;
    @GetMapping("/login/key")
    @ResponseBody
    public XczxResult loginKey(){
        log.info("{}",port);
        String state = UUID.randomUUID().toString();
        CacheUtil.resultMap.put(state,null );
        //TODO 返回随机字符串
        LoginKeyResult loginKeyResult = new LoginKeyResult();
        loginKeyResult.setState(state);
        UriComponents build = UriComponentsBuilder.fromUriString(xczxOauth2ClientProperties.getAuth().getServerUrl())

                .queryParam("client_id", xczxOauth2ClientProperties.getAuth().getClientId())
                .queryParam("response_type", "code")
                .queryParam("scope", xczxOauth2ClientProperties.getAuth().getScope())
                .queryParam("state", state)
                .queryParam("redirect_uri",xczxOauth2ClientProperties.getAuth().getRedirectUri())
                .build();

        loginKeyResult.setLoginUrl(build.toUriString());
        return XczxResult.success(loginKeyResult);
    }


    @GetMapping("/login/user")
    @ResponseBody
    public XczxResult loginUser(@RequestParam String state){
        //TODO 查询用户是否授权成功
        return XczxResult.success(CacheUtil.resultMap.get(state));
    }

    @GetMapping("/redirect")
    public String redirect(@RequestHeader(HttpHeaders.HOST) String host){
        return "redirect:http://"+host;
    }

    @GetMapping("/login/oauth2/code/hello")
    public String loginCode(String key, String code, String state, HttpServletResponse response, HttpServletRequest httpServletRequest) throws IOException {
        String access_token="";
        log.info("code:{}",code);
//        POST http://localhost:9000/oauth2/token?code={{authCode}}&grant_type=authorization_code&redirect_uri=http://client:8080/login/oauth2/code/login-client&scope=openid%20profile
        String grant_type="authorization_code";
        String redirect_uri=xczxOauth2ClientProperties.getAuth().getRedirectUri();
        String scope=xczxOauth2ClientProperties.getAuth().getRedirectUri();
        String result=authClient.getToken(code,grant_type,redirect_uri,scope,"");

        CacheUtil.resultMap.put(state, JSONObject.parseObject(result, Oauth2TokenResult.class));
        response.setHeader("token", JSONObject.toJSONString(result));
        return "success";
//        return  "redirect:http://localhost:8080/success.html";
    }

    private Environment environment;
    @Override
    public void setEnvironment(Environment environment) {
        this.environment=environment;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.port= Integer.parseInt(environment.getProperty("server.port"));
    }
}
